const express = require('express');
const router = express.Router();
const request = require('request');
const {AppID, AppSecret} = require("../config/config").appInfo;

router.post('/', (req, res, next)=>{
    var code = req.body.code;
    var api = `https://api.weixin.qq.com/sns/jscode2session?appid=${AppID}&secret=${AppSecret}&js_code=${code}&grant_type=authorization_code`;
    request(api, (err, response, body)=>{
        if (err) throw err;
        if (response.statusCode == 200) {
            var data = JSON.parse(body);
            if ('openid' in data) {
                res.send({
                    code: response.statusCode,
                    openid: data.openid,
                });
            }else{
                res.send({
                    code: response.statusCode,
                    openid: null,
                });
            }
        }else{
            res.send({
                code: response.statusCode
            });
        }
    });
});
module.exports = router;